package cn.bone.mqtt.demo02;

import com.alibaba.fastjson.JSON;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by MD-01 on 2017/4/21.
 */
public class MyCallBack implements MqttCallback {

    private Logger logger = LoggerFactory.getLogger(MqttCallback.class);
    private MqttClient client;
    private int index;

    public MyCallBack(MqttClient client,int index){
        this.client = client;
        this.index = index;
    }

    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接丢失:"+cause.getMessage());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        logger.info("收到消息.topic:"+topic+
                "  msg:"+ new String(message.getPayload(),"UTF-8")+
                "  qos:" + message.getQos()+
                "  id:" + message.getId() +
                "  duplicate:" + message.isDuplicate() +
                "  retained:" + message.isRetained());
        if(index%3==0){
            client.messageArrivedComplete(message.getId(),message.getQos());
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        logger.info("发送完成:"+ JSON.toJSONString(token));
    }
}
